<template>
  <div class="container" style="height: 100%">
    <div class="flex_cm" style="height: 100%">
      <search
        :data="header_list"
        @changeIsShow="
          (e) => {
            header_list[e].isShow = !header_list[e].isShow
            header_list[e].value = ''
          }
        "
        @search="search_key"
        @reset="
          header_list.forEach((item) => {
            item.value = ''
          }),
            search_key()
        "
      ></search>
      <div class="flex_js bg_fff" style="flex: 1; align-items: flex-start">
        <div
          style="width: 40%; position: relative; height: 100%; padding: 10px"
        >
          <div class="flex_js m_bottom10">
            <div>字典列表</div>
            <el-button
              type="primary"
              @click="add_box = true"
              v-if="has_role_list_1[3].has_role"
              >新增</el-button
            >
          </div>
          <el-table
            style="text-align: center"
            :data="dict_list_1"
            :max-height="max_height"
            border
            v-loading="loadding_1"
            ref="dictTable"
            highlight-current-row
            :row-class-name="
              ({ row, rowIndex }) => {
                row.index = rowIndex
              }
            "
            @row-click="
              (row) => {
                get_list_info(row)
              }
            "
          >
            <el-table-column
              label="序号"
              width="100"
              type="index"
            ></el-table-column>
            <el-table-column
              v-if="header_list[0].showTable"
              prop="name"
              label="字典名称"
              sortable
            ></el-table-column>
            <el-table-column
              v-if="header_list[1].showTable"
              label="备注"
              sortable
              prop="remark"
              ><template #default="scope: any"
                ><div class="text_over">
                  <el-tooltip :content="scope.row.remark" placement="bottom">
                    {{ scope.row.remark }}
                  </el-tooltip>
                </div></template
              ></el-table-column
            >
            <el-table-column
              label="操作"
              width="124px"
              v-if="environment == 'development'"
            >
              <template #default="scope: any">
                <div class="flex_cc">
                  <el-tooltip
                    content="编辑"
                    placement="bottom"
                    v-if="has_role_list_1[1].has_role"
                  >
                    <svgBtn
                      icon="table_edit"
                      style="font-size: 20px"
                      @click="update_dict({ type: 1, data: scope.row })"
                    ></svgBtn>
                  </el-tooltip>
                  <el-tooltip
                    style="margin-left: 20px"
                    content="删除"
                    placement="bottom"
                    v-if="has_role_list_1[2].has_role"
                  >
                    <svgBtn
                      icon="table_delete"
                      style="font-size: 20px; margin-left: 20px"
                      @click="delete_dict({ type: 1, data: scope.row })"
                    ></svgBtn>
                  </el-tooltip>
                </div>

                <!-- <table_edit
                :status="false"
                :role="has_role_list_1"
                @edit_item="update_dict({ type: 1, data: scope.row })"
                @delete_item="delete_dict({ type: 1, data: scope.row })"
              ></table_edit> -->
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            class="m_10_0 pagination"
            style="bottom: 20px"
            v-model:currentPage="form_data_0.current"
            v-model:page-size="form_data_0.pageSize"
            :page-sizes="[5, 10, 20, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="list_total"
            @size-change="
              (e) => {
                form_data_0.pageSize = e
                get_list()
              }
            "
            @current-change="
              (e) => {
                form_data_0.current = e
                get_list()
              }
            "
          />
        </div>
        <div style="width: 0.5%; height: 100%; background-color: #f0f2f5"></div>
        <div
          style="width: 59%; padding: 10px; position: relative; height: 100%"
        >
          <div class="flex_js m_bottom10">
            <div>字典值数据</div>
            <el-button
              type="primary"
              @click="add_box_children = true"
              v-if="has_role_list_2[3].has_role"
              >新增</el-button
            >
          </div>
          <el-table
            style="text-align: center"
            :data="dict_list_2"
            :max-height="max_height"
            border
            v-loading="loadding_2"
            highlight-current-row
            :default-sort="{ prop: 'name', order: 'name' }"
          >
            <el-table-column
              prop="dictCode"
              label="编码"
              width="100"
            ></el-table-column>
            <el-table-column
              v-if="header_list[0].showTable"
              sortable
              prop="dictValue"
              label="名称"
            ></el-table-column>
            <el-table-column
              v-if="header_list[1].showTable"
              sortable
              label="备注"
              prop="remark"
              ><template #default="scope: any"
                ><div class="text_over">
                  <el-tooltip :content="scope.row.remark" placement="bottom">
                    {{ scope.row.remark }}
                  </el-tooltip>
                </div></template
              ></el-table-column
            >
            <el-table-column
              label="操作"
              width="124px"
              v-if="environment == 'development'"
            >
              <template #default="scope: any">
                <div class="flex_cc">
                  <el-tooltip
                    content="编辑"
                    placement="bottom"
                    v-if="has_role_list_2[1].has_role"
                  >
                    <svgBtn
                      icon="table_edit"
                      style="font-size: 20px"
                      @click="update_dict({ type: 2, data: scope.row })"
                    ></svgBtn>
                  </el-tooltip>
                  <el-tooltip
                    style="margin-left: 20px"
                    content="删除"
                    placement="bottom"
                    v-if="has_role_list_2[2].has_role"
                  >
                    <svgBtn
                      icon="table_delete"
                      style="font-size: 20px; margin-left: 20px"
                      @click="delete_dict({ type: 2, data: scope.row })"
                    ></svgBtn>
                  </el-tooltip>
                </div>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            class="m_10_0 pagination"
            style="bottom: 20px"
            v-model:currentPage="form_data_1.current"
            v-model:page-size="form_data_1.pageSize"
            :page-sizes="[5, 10, 20, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="children_total"
            @size-change="
              (e) => {
                form_data_1.pageSize = e
                get_list_info({
                  id: dict_list_1[currentRowIndex].id,
                  name: dict_list_1[currentRowIndex].name,
                  index: currentRowIndex,
                })
              }
            "
            @current-change="
              (e) => {
                form_data_1.current = e
                get_list_info({
                  id: dict_list_1[currentRowIndex].id,
                  name: dict_list_1[currentRowIndex].name,
                  index: currentRowIndex,
                })
              }
            "
          />
        </div>
      </div>
    </div>
    <el-drawer
      v-model="add_box"
      direction="rtl"
      @close="resetForm(ruleAddDictForm)"
      :close-on-click-modal="false"
    >
      <template #title>
        <h4 v-if="form_data.id == ''">新增字典类型</h4>
        <h4 v-else>修改字典类型</h4>
      </template>
      <template #default>
        <el-form
          :model="form_data"
          label-width="80px"
          :rules="rules"
          ref="ruleAddDictForm"
        >
          <el-form-item label="名称" prop="name">
            <el-input
              v-model="form_data.name"
              placeholder="请输入"
              show-word-limit
              maxlength="30"
            ></el-input>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="form_data.remark"
              placeholder="请输入"
              show-word-limit
              maxlength="30"
            ></el-input>
          </el-form-item>
          <div class="tr">
            <el-button @click="resetForm(ruleAddDictForm)">取消</el-button>
            <el-button type="primary" @click="add_submit(ruleAddDictForm)"
              >确定</el-button
            >
          </div>
        </el-form>
      </template>
    </el-drawer>
    <el-drawer
      v-model="add_box_children"
      direction="rtl"
      @close="resetForm(ruleAddDicChildtForm)"
      :close-on-click-modal="false"
    >
      <template #title>
        <h4 v-if="form_data_children.id == ''">
          新增 {{ form_data_1.dictName }} - 字典值数据
        </h4>
        <h4 v-else>修改 {{ form_data_1.dictName }} - 字典值数据</h4>
      </template>
      <template #default>
        <el-form
          :model="form_data_children"
          label-width="80px"
          :rules="rules"
          ref="ruleAddDicChildtForm"
        >
          <el-form-item label="编码" prop="dictCode">
            <el-input
              v-model="form_data_children.dictCode"
              placeholder="请输入"
              show-word-limit
              maxlength="30"
            ></el-input>
          </el-form-item>
          <el-form-item label="名称" prop="dictValue">
            <el-input
              v-model="form_data_children.dictValue"
              placeholder="请输入"
              show-word-limit
              maxlength="30"
            ></el-input>
          </el-form-item>
          <el-form-item label="备注">
            <el-input
              v-model="form_data_children.remark"
              placeholder="请输入"
              show-word-limit
              maxlength="30"
            ></el-input>
          </el-form-item>
          <div class="tr">
            <el-button @click="resetForm(ruleAddDicChildtForm)">取消</el-button>
            <el-button
              type="primary"
              @click="add_children_submit(ruleAddDicChildtForm)"
              >确定</el-button
            >
          </div>
        </el-form>
      </template>
    </el-drawer>
    <dialog_box
      @submit_delete="submit_delete"
      @close="show_delete_box = false"
      :show_delete_box="show_delete_box"
      :delete_name="delete_name"
    ></dialog_box>
  </div>
</template>

<script lang="ts" setup>
import { check_role } from '@/utils/utils'
import dialog_box from '@/view/components/dialog_box.vue'
import table_edit from '@/view/components/table_edit.vue'
import search from '@/view/components/search.vue'
import { onMounted, ref, onUnmounted, nextTick } from 'vue'
import { FormInstance, ElMessage, ElMessageBox } from 'element-plus'
import axios from '@/service/HttpRequest'
import serviceApi from '@/service/api'
import EventBus from '@/utils/EventBus'
import svgBtn from '@/components/svg_button.vue'

const environment = process.env.NODE_ENV
console.log(environment)
const rules = ref({
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  remark: [{ required: true, message: '请输入备注', trigger: 'blur' }],
  dictCode: [{ required: true, message: '请输入编码', trigger: 'blur' }],
  dictValue: [{ required: true, message: '请输入名称', trigger: 'blur' }],
})
const has_role_list_1 = ref([
  { path: '', has_role: false },
  { path: 'dictType/put', has_role: false },
  { path: 'dictType/delete', has_role: false },
  { path: 'dictType/post', has_role: false },
])
const has_role_list_2 = ref([
  { path: '', has_role: false },
  { path: 'dictData/put', has_role: false },
  { path: 'dictData/delete', has_role: false },
  { path: 'dictData/post', has_role: false },
])
const ruleAddDictForm = ref<FormInstance>()
const ruleAddDicChildtForm = ref<FormInstance>()
const header_list = ref([
  {
    label: '字典名称',
    value: '',
    showTable: true,
    type: 'input',
    isShow: true,
    options: [],
  },
  {
    label: '备注',
    value: '',
    showTable: true,
    type: 'input',
    isShow: false,
    options: [],
  },
])
const add_box = ref(false)
const add_box_children = ref(false)
const dict_list_1 = ref([])
const dict_list_2 = ref([])
const list_total = ref()
const children_total = ref()
const loadding_1 = ref(false)
const loadding_2 = ref(false)
const form_data = ref({
  id: '',
  name: '',
  remark: '',
  status: true,
})
const form_data_0 = ref({
  current: 1,
  name: '',
  remark: '',
  pageSize: 10,
})
const form_data_children = ref({
  id: '',
  dictValue: '',
  dictCode: '',
  remark: '',
  dictTypeId: '',
  status: true,
})
const form_data_1 = ref({
  current: 1,
  dictTypeId: '',
  dictName: '',
  pageSize: 10,
})
const currentRowIndex = ref(0)
onMounted(() => {
  EventBus.on('refresh', async () => {
    await get_list()
    ElMessage.success('刷新成功！')
  })
  get_list()
})
onUnmounted(() => {
  EventBus.off('refresh')
})
const max_height = ref()
nextTick(() => {
  has_role_list_1.value.forEach((item) => {
    item.has_role = check_role(item.path)
  })
  has_role_list_2.value.forEach((item) => {
    item.has_role = check_role(item.path)
  })
  max_height.value = window.innerHeight - 320 // 不带分页的 table 高度
})
const dictTable = ref()
const search_key = () => {
  currentRowIndex.value = 0
  console.log(header_list.value)
  form_data_0.value.name = header_list.value[0].value
  form_data_0.value.remark = header_list.value[1].value
  get_list()
}
const add_children_submit = async (formEl: FormInstance | undefined) => {
  await formEl.validate((valid) => {
    console.log(valid)
    if (valid) {
      axios
        .request({
          url:
            form_data_children.value.id == ''
              ? serviceApi.add_dict_children
              : serviceApi.add_dict_children +
                '/' +
                form_data_children.value.id,
          method: form_data_children.value.id == '' ? 'post' : 'put',
          data: form_data_children.value,
        })
        .then((res) => {
          console.log(res)
          setTimeout(() => {
            form_data_children.value = {
              id: '',
              dictValue: '',
              dictCode: '',
              dictTypeId: '',
              remark: '',
              status: true,
            }
            add_box_children.value = false
            get_list_info({ id: form_data_1.value.dictTypeId })
          }, 1000)
        })
        .catch((error) => {
          ElMessage.error(error)
        })
    }
  })
}
const get_list = () => {
  loadding_1.value = true
  // 字典数据
  axios
    .request({
      url: serviceApi.dict_list,
      method: 'POST',
      data: form_data_0.value,
    })
    .then((res) => {
      if (!res.data.content.length) {
        loadding_1.value = false
        dict_list_1.value = []
        dict_list_2.value = []
        list_total.value = 0
        children_total.value = 0
        return
      }
      dict_list_1.value = res.data.content
      list_total.value = parseInt(res.data.totalElements)
      nextTick(() => {
        dictTable.value.setCurrentRow(dict_list_1.value[currentRowIndex.value])
        if (res.data.content.length != 0)
          get_list_info({
            id: dict_list_1.value[currentRowIndex.value].id,
            name: dict_list_1.value[currentRowIndex.value].name,
            index: currentRowIndex.value,
          })
      })
      loadding_1.value = false
    })
    .catch((error) => {
      ElMessage.error(error)
      loadding_1.value = false
    })
}
const get_list_info = (e) => {
  console.log(currentRowIndex.value, e.index)
  loadding_2.value = true
  currentRowIndex.value = e.index ? e.index : currentRowIndex.value
  form_data_1.value.dictTypeId = e.id
  form_data_1.value.dictName = e.name ? e.name : form_data_1.value.dictName
  form_data_children.value.dictTypeId = e.id
  let timer
  if (timer) {
    clearTimeout(timer)
  }
  //设置定时器，规定时间后执行真实要执行的函数
  timer = setTimeout(() => {
    axios
      .request({
        url: serviceApi.dict_children_list,
        method: 'post',
        data: form_data_1.value,
      })
      .then((res) => {
        dict_list_2.value = res.data.content
        children_total.value = parseInt(res.data.totalElements)
        loadding_2.value = false
      })
      .catch((error) => {
        ElMessage.error(error)
        loadding_2.value = false
      })
  }, 100)
}
const show_delete_box = ref(false)
const delete_id = ref()
const delete_type = ref()
const delete_name = ref()
const submit_delete = () => {
  axios
    .request({
      url:
        delete_type.value == 2
          ? serviceApi.add_dict_children + '/' + delete_id.value
          : serviceApi.dict_add + '/' + delete_id.value,
      method: 'delete',
    })
    .then((res) => {
      ElMessage.success('删除成功！')
      setTimeout(() => {
        show_delete_box.value = false
        delete_type.value == 1
          ? get_list()
          : get_list_info(dict_list_1.value[currentRowIndex.value])
      }, 1000)
    })
    .catch((error) => {
      ElMessage.error(error)
    })
}
const delete_dict = (e) => {
  delete_id.value = e.data.id
  delete_type.value = e.type
  show_delete_box.value = true
  delete_name.value = e.type == 1 ? e.data.name : e.data.dictValue
}
const update_dict = (e) => {
  console.log(e)
  if (e.type == 1) {
    form_data.value = {
      id: e.data.id,
      name: e.data.name,
      remark: e.data.remark,
      status: true,
    }
    add_box.value = true
  } else {
    form_data_children.value = {
      id: e.data.id,
      dictValue: e.data.dictValue,
      remark: e.data.remark,
      dictTypeId: form_data_children.value.dictTypeId,
      dictCode: e.data.dictCode,
      status: true,
    }
    add_box_children.value = true
  }
}

const add_submit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid) => {
    console.log(valid)
    if (valid) {
      axios
        .request({
          url:
            form_data.value.id == ''
              ? serviceApi.dict_add
              : serviceApi.dict_add + '/' + form_data.value.id,
          method: form_data.value.id == '' ? 'post' : 'put',
          data: form_data.value,
        })
        .then((res) => {
          console.log(res)
          setTimeout(() => {
            form_data.value = {
              id: '',
              name: '',
              remark: '',
              status: true,
            }
            add_box.value = false
            get_list()
          }, 1000)
        })
        .catch((error) => {
          ElMessage.error(error)
        })
    }
  })
}
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  form_data.value = {
    id: '',
    name: '',
    remark: '',
    status: true,
  }
  form_data_children.value = {
    id: '',
    dictValue: '',
    dictCode: '',
    remark: '',
    dictTypeId: form_data_children.value.dictTypeId,
    status: true,
  }
  add_box.value = false
  add_box_children.value = false
}
</script>

<style lang="scss" scoped></style>
